package com.jf3q.iot.netty;

import com.jf3q.iot.service.SendInstructsService;
import com.jf3q.iot.utils.SpringUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;
@Slf4j

public class NettyServerHandler extends ChannelInboundHandlerAdapter {


    private static final SendInstructsService sendInstructsService = SpringUtils.getBean("sendInstructsService");
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);


    public static ChannelGroup getChannelGroup() {
        return channelGroup;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        Channel channel = ctx.channel();
        log.info("有客户端{}上线",channel.remoteAddress());

        //将当前channel 加入到channeLGroup
        channelGroup.add(channel);

        //修改网关状态
    }


  //接收到客户端给服务端发的消息
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //可以修改  电表设备的状态
        String returnStr=(String) msg;
        log.info("channelRead:read msg:"+msg);

        sendInstructsService.callbackInstructResultMsg(returnStr);

    }




    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 修改网关状态
        log.info("有客户端离线");

    }
}
